"""
装饰器就是闭包函数的语法糖
闭包: 是参数和返回值都是函数类型函数
"""


def wrapper1(func):

    def improved_func(*args, **kwargs):
        print("wrapper1 before")
        res = func(*args, **kwargs)
        print("wrapper1 after")
        return res

    return improved_func


def wrapper2(func):

    def improved_func(*args, **kwargs):
        print("wrapper2 before")
        res = func(*args, **kwargs)
        print("wrapper2 after")
        return res

    return improved_func


def wrapper3(func):

    def improved_func(*args, **kwargs):
        print("wrapper3 before")
        res = func(*args, **kwargs)
        print("wrapper3 after")
        return res

    return improved_func


# 带参数的装饰器
def wrapper_with_para(info):
    def middle(func):
        def inner(*args, **kwargs):
            print("wrapper with para before" + info)
            print("info is :" + info)
            res = func(*args, **kwargs)
            print("wrapper with para after")
            return res

        return inner

    return middle


def func(n):
    print("func running")
    count = 0
    for i in range(n):
        if i % 2 == 0:
            count += 1
    return count


@wrapper1
@wrapper2
@wrapper3
def func2(n):
    print("func2 running")
    count = 0
    for i in range(n):
        if i % 2 == 1:
            count += 1
    return count


@wrapper_with_para("information")
def func3(n):
    print("func3 running")
    count = 0
    for i in range(n):
        if i % 2 == 0:
            count += 1
    return count


if __name__ == "__main__":
    print("======增强前=======")
    print(func(10))

    print("======增强后(不带参数的装饰器)=======")
    func = wrapper1(func)  # 闭包形式增强
    print(func.__name__)
    print(func(10))

    print("======增强后(带参数的装饰器)=======")
    print(func3(10))

    print("======多个装饰器增强后=======")
    func2(10)
